package com.shaonianyou;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.dialect.IDialect;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ITemplateResolver;

import com.google.common.collect.Sets;
import com.shaonianyou.component.WxMappingJackson2HttpMessageConverter;

@SpringBootApplication
@Controller
//@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebApplication extends WebMvcConfigurerAdapter {

	public static void main(String[] args) {
		SpringApplication.run(WebApplication.class, args);
	}

	@RequestMapping("/index")
	public String index() {
		return "index";
	}

	@Autowired
	private final Collection<ITemplateResolver> templateResolvers = Collections.emptySet();

	@Autowired(required = false)
	private final Collection<IDialect> dialects = Collections.emptySet();

	@Bean
	public SpringTemplateEngine templateEngine() {
		SpringTemplateEngine engine = new SpringTemplateEngine();
		for (ITemplateResolver templateResolver : this.templateResolvers) {
			engine.addTemplateResolver(templateResolver);
		}

		for (IDialect dialect : this.dialects) {
			engine.addDialect(dialect);
		}
		Set<IDialect> s = Sets.newHashSet();
		s.add(new SpringSecurityDialect());
		engine.setAdditionalDialects(s);
		return engine;
	}

	@Bean
	public RequestMatcher csrfSecurityRequestMatcher() {
		RequestMatcher matcher = new RequestMatcher() {

			private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");

			@Override
			public boolean matches(HttpServletRequest request) {
				String servletPath = request.getServletPath();
				if (servletPath.contains("/logout"))
					return false;
				return !allowedMethods.matcher(request.getMethod()).matches();
			}
		};

		return matcher;
	}
	
	@Bean
	RestTemplate restTemplate(){
	    RestTemplate restTemplate = new RestTemplate();
	    restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
	    return restTemplate;
	}
	
	/*@Bean
	public ApplicationSecurity applicationSecurity() {
		return new ApplicationSecurity();
	}
	

	@Override
	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/login").setViewName("login");
	}*/

	

}
